<script></script>
 <div class="ibox float-e-margins" id="wo_window">
  <!-- Supervisor -->
  <?php $omg;?>
  <?php foreach ($wo_data as $t): $req_stat=$t->stat_req;  $g_req_id = $t->inv_request_id;?>
            <input type="hidden" id="maintain_id_2" value="<?php echo $t->maintain_id; ?>">
            <input type="hidden" id="acct" value="<?php echo $t->account_id; ?>">
            <input type="hidden" id="work_type" value="<?php echo $t->maintain_code; ?>">
            <input type="hidden" id="maintain_code_2" value="<?php echo $t->maintain_code; ?>">
         <?php endforeach;?>
  <?php if ($operation == "edit") {
	?>
    <form id="edit_wo_form" class="form-horizontal"  method="post">
      <div class="ibox-title" style="border:none;"><h5 style="color: #00afef"><i>Edit Work Order</i></h5>
        <div class="ibox-tools">
            <button  id="edits" class="btn btn-sm btn-primary save-btn-tab">Save</button>
            <a id = "cancel_edit" class="btn btn-sm btn-outline btn-info cancel-btn-tab">Cancel</a>
            <a style="display:none;" id="complete_btn_edit" class="btn btn-sm btn-outline btn-info cancel-btn-tab">Complete</a>
        </div>
      </div>
        <div class="ibox-content">
           <?php foreach ($wo_data as $wo_datus) {
		?>
           <input type="hidden" name="h_maintain_id" value="<?php echo $wo_datus->maintain_id; ?>">
           <input type="hidden" name="c_acct" value="<?php echo $wo_datus->account_id; ?>">
            <div class="form-group">
                <label class="col-lg-3 control-label">Maintenance Type</label>
                    <div class="col-lg-4">
                        <select id="" class="chosen-select" name="" disabled>
                        <?php foreach ($wo_type as $wo) {?>
                            <option value="<?php echo $wo->lookup_code; ?>" <?php echo ($wo_datus->maintain_code == $wo->lookup_code ? 'selected' : ''); ?> ><?php echo $wo->meaning; ?></option>
                        <?php }
		?>
                    </select>
                    </div>
            </div>
            <div class="form-group">
                <label class="col-lg-3 control-label">Account Name</label>
                    <div class="col-lg-4">
                        <input type="text" placeholder="" name="" id="account_id" class="form-control" value="<?php echo $wo_datus->acct_name; ?>" readonly>
                    </div>
            </div>
            <div class="form-group">
                <label class="col-lg-3 control-label">Assigned to</label>
                    <div class="col-lg-4">
                        <select id="assgn_to" class="chosen-select" name="edit_wo_assign">
                        <?php foreach ($assgn as $op) {?>
                            <option value="<?php echo $op->user_id; ?>" ><?php echo $op->user_name; ?></option>
                        <?php }
		?>
                        </select>
                    </div>
            </div>
            <div class="form-group">
                <label class="col-lg-3 control-label">Target Date</label>
                    <div class="col-lg-4">
                        <input type="search" placeholder="" name="edit_target_date" id="e_t_date" class="form-control" value="<?php echo $wo_datus->target_date; ?>">
                    </div>
            </div>
            <?php }
	?>
        </div>
    </form>
    <?php $omg = $wo_datus->maintain_code;} else if ($operation == "com") {
	?>

<!-- Operator -->
<?php ?>
    <form id="complete_wo_form" class="form-horizontal"  method="post">
      <div class="ibox-title" style="border:none;"><h5 style="color: #00afef"><i>Complete Work Order</i></h5>
        <div class="ibox-tools">
            <button  id="edits" class="btn btn-sm btn-primary">Save</button>
            <a id = "cancel_edit" class="btn btn-sm btn-outline btn-info">Cancel</a>
            <a style="display:none;" id="complete_btn_edit" class="btn btn-sm btn-outline btn-info cancel-btn-tab">Complete</a>
        </div>
      </div>
        <div class="ibox-content">
           <?php foreach ($wo_data as $wo_datus) {
		?>
           <input type="hidden" name="h_c_maintain_id"    value="<?php echo $wo_datus->maintain_id; ?>">
           <input type="hidden" name="c_wo_code" id="cwo" value="<?php echo $wo_datus->maintain_code; ?>">
           <input type="hidden" name="c_acct"    id=""    value="<?php echo $wo_datus->account_id; ?>">
            <div class="form-group">
                <label class="col-lg-3 control-label">Maintenance Type</label>
                    <div class="col-lg-4">
                        <select id="" class="chosen-select" name="" disabled>
                        <?php foreach ($wo_type as $wo) {?>
                            <option value="<?php echo $wo->lookup_code; ?>" <?php echo ($wo_datus->maintain_code == $wo->lookup_code ? 'selected' : ''); ?> ><?php echo $wo->meaning; ?></option>
                        <?php }
		?>
                    </select>
                    </div>
            </div>
            <div class="form-group">
                <label class="col-lg-3 control-label">Account Name</label>
                    <div class="col-lg-4">
                        <input type="text" placeholder="" name="" id="" class="form-control" value="<?php echo $wo_datus->acct_name; ?>" readonly>
                    </div>
            </div>
            <div class="form-group">
                <label class="col-lg-3 control-label">Assigned to</label>
                    <div class="col-lg-4">
                        <select id="assgn_to" class="chosen-select" name="" disabled>
                        <?php foreach ($assgn as $op) {?>
                            <option value="<?php echo $op->user_id; ?>" ><?php echo $op->user_name; ?></option>
                        <?php }
		?>
                        </select>
                    </div>
            </div>
            <div class="form-group">
                <label class="col-lg-3 control-label">Target Date</label>
                    <div class="col-lg-4">
                        <input type="search" placeholder="" name="" id="" class="form-control" value="<?php echo $wo_datus->target_date; ?>" readonly>
                    </div>
            </div>
            <div class="form-group">
                <label class="col-lg-3 control-label">Last Meter Reading</label>
                    <div class="col-lg-4">
                        <input type="text" placeholder="" name="wo_last_reading" id="last_r" class="form-control" value="<?php echo $wo_datus->last_meter_reading; ?>" >
                    </div>
            </div>
            <div class="form-group">
                <label class="col-lg-3 control-label">New Meter Reading</label>
                    <div class="col-lg-4">
                        <input type="text" placeholder="" name="wo_new_reading" id="new_r" class="form-control" value="<?php echo $wo_datus->new_meter_reading; ?>" >
                    </div>
            </div>
            <?php }
	?>
        </div>
    </form>
    <?php $omg = $wo_datus->maintain_code; }
//echo $omg;
?>
<div class="ibox-title" style="border: none;">
    <button style="display: <?php echo $omg == 'NEW' || $omg == 'REP' ? '' : 'none'; ?>;" id="add_dev_btn_2" type="button" class="btn btn-w-m btn-info add-tab-btn">Add Device</button></h4>
    <button style="display: none;" id="dev_info" type="button" class="btn btn-w-m btn-white">Device Info</button></h4>
    <?php if($req_stat == 'N/A'){?>
      <button  style="display: <?php echo $omg == 'NEW' || $omg == 'REP' ? '' : 'none'; ?>" id="req_add" class="btn btn-w-m btn-info ">Create Item Request</button>
    <?php }

    //if($req_stat == 'REQ_SUBMITTED'){  ?> 
      <button  style="display: <?php echo (($omg == 'NEW' || $omg == 'REP') && $req_stat == 'REQ_SUBMITTED' ? '' : 'none'); ?>" id="req_upd" class="btn btn-w-m btn-info ">Update Item Request</button>
    <?php //} ?>
    <button style="display: none;" id="dev_info" type="button" class="btn btn-w-m btn-white">Device Info</button></h4>
</div>

<div style="display: none;" id="device_window_e">
    <div class="ibox-title" style="border:none;"><h5 style="color: #00afef"><i id="tits"></i></h5>
        <div class="ibox-tools">
            <button id="save_device_2" class="btn btn-sm btn-primary save-btn-tab">Save</button>
            <button style="display:none;" id="save_edit_device_2" class="btn btn-sm btn-primary save-btn-tab">Save</button>
            <!-- <button id="cancel_add_device_2" class="btn btn-sm btn-outline btn-info cancel-btn-tab">Cancel</button> -->
        </div>
    </div>
    <div class="ibox-content">
       <form class="form-horizontal" id="device_form_e">
          <input type="hidden" name="account_id" value="">
          <input type="hidden" name="status">
          <input type="hidden" name="device_ass_id" value="">
          <div class="form-group">
              <label class="col-lg-3 control-label">Item Number</label>
              <div class="col-lg-7">
                  <select class="form-control m-b chosen-select" name="item_num">
                      <option value="">Select Item Number</option>
                      <?php foreach ($item as $i): ?>
                      <option value="<?php echo $i->item_id; ?>"><?php echo $i->item_num; ?></option>
                      <?php endforeach;?>
                  </select>
              </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Device Type</label>
              <div class="col-lg-7">
                  <select class="form-control m-b chosen-select" name="dev_type">
                      <option value="">Select Device Type</option>
                      <?php foreach ($devtype as $dt): ?>
                      <option value="<?php echo $dt->type; ?>"><?php echo $dt->meaning; ?></option>
                      <?php endforeach;?>
                  </select>
              </div>
          </div>
           <div class="form-group">
              <label class="col-lg-3 control-label">Model Number</label>
              <div class="col-lg-7">
                  <input type="text" name="model_number" class="form-control" value=''>
              </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Serial Number</label>
              <div class="col-lg-7">
                  <input type="text" name="serial_number" value='' class="form-control">
              </div>
          </div>
           <div class="form-group">
              <label class="col-lg-3 control-label">Device ID</label>
              <div class="col-lg-7">
                  <input   type="text" name="dev_id" value='' class="form-control">
              </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Mother Meter</label>
              <div class="col-lg-7">
                  <select class="form-control m-b chosen-select" name="mom_meter">
                      <?php foreach ($mom_meter as $mm): ?>
                      <option value="<?php echo $mm->mmeter_id; ?>"><?php echo $mm->mother_name; ?></option>
                      <?php endforeach;?>
                  </select>
              </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Location Latitude</label>
              <div class="col-lg-7">
                  <input type="text" value="0" name="e_devLat" placeholder="Point your location in the map below" class="form-control" id="e_dlat" readonly required>
              </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Location Longitude</label>
              <div class="col-lg-7">
                  <input type="text" value="0" name="e_devLng" placeholder="Point your location in the map below" class="form-control" id="e_dlng" readonly required>
              </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Pick Location</label>
              <div class="col-lg-6">
                  <div id="map_wrapper" style="height: 300px;">
                      <div id="map_canvas" class="mapping" style="width: 100%;height: 100%;">
                      </div>
                  </div>
              </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Device Remarks</label>
              <div class="col-lg-7">
                  <input type="text" name="dev_remarks" value='' class="form-control">
              </div>
          </div>
      </form>
    </div><!-- end ofibox-content -->

    

  </div>
  <input type="hidden" id="add_dev_click" value="0">
  <input type="hidden" id="hasDevice" value="">
</div>

<div class="ibox float-e-margins" id="request_window" style='display:none'> 
      <div class="ibox-title" style="border:none;"><h5 style="color: #00afef"><i>Add<i></h5>
        <div class="ibox-tools" id="ins_req">    
             <a class="btn btn-primary btn-sm save-btn-tab" id="submit_req_add">Save</a>
             <a id="back_woa" class="btn btn-sm btn-outline btn-info cancel-btn-tab">Cancel</a>
        </div>
        <div class="ibox-tools" id="upd_req">    
             <a class="btn btn-primary btn-sm save-btn-tab" id="submit_req_upd">Save</a>
             <a id="back_wo" class="btn btn-sm btn-outline btn-info cancel-btn-tab">Cancel</a>
        </div>
     </div>
    <div class="ibox-content">
          <form  class="form-horizontal" id="wo_add_req">
            <div class="form-group" >
                <label class="col-lg-3 control-label">Request Number:</label>
                <div class="col-lg-5">
                    <input type="text" id="" class="form-control" name="request_num" value="<?php echo $req_num[0]->val; ?>" readonly>
                </div>
             </div>
             <div class="form-group">
                <label class="col-lg-3 control-label">Request Date:</label>
                 <div class="col-lg-5">
                    <input type="date" id="" class="form-control" name="request_date">
                </div>
            </div>
            <div class="form-group">
                <label class="col-lg-3 control-label">Requested By:</label>
                 <div class="col-lg-5">
                    <select class = "chosen-select" name="request_by" id ="req_by_e">
                      <option value=""> -- </option>
                      <?php foreach ($users as $usr) { ?>
                        <option value="<?php echo $usr->user_id; ?>" id=""><?php echo $usr->user_name." (".$usr->last_name.", ".$usr->first_name.")"; ?></option>
                      <?php } ?>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-lg-3 control-label">Approved By:</label>
                <div class="col-lg-5">
                    <input type="text" id="" class="form-control" name="approve_by" readonly>
                </div>
            </div>
            <div class="form-group">
                <label class="col-lg-3 control-label">Status:</label>
                <div class="col-lg-5">
                    <select class = "chosen-select" name="request_stat" id ="req_stat">
                      <!-- <option value=""> -- </option> -->
                      <?php foreach ($status as $stat) { ?>
                        <option value="<?php echo $stat->lookup_code; ?>" id="" <?php echo ($stat->lookup_code == 'REQ_SUBMITTED' ? 'selected' : ''); ?> ><?php echo $stat->meaning; ?></option>
                      <?php } ?>
                    </select>
                </div>
            </div>
          </form>
          <div id="req_content">
          <div id="" class="ibox-content">
            <h3 style="color: #00afef">Requested Item</h3>
              <form  id="req_add_content" class="form-inline">
                <input type="hidden" id="req_id" name="c_req_id" value="">
                  <table id="pgTable"class="table table-bordered" style="width:80%;">
                    <thead>
                      <tr>
                        <th style="width:100px;">Sequence</th>
                        <th>Item</th>
                        <th style="width:100px;">Qty</th>
                        <th style="width:50px;">Action</th>
                      </tr>
                      <tr>
                        <td style="margin:0px;padding:0px;">
                            <input style="width:100%;text-align: right;" type="text" id="req_seq" name="req_sequence" class="form-control-custom">
                        </td>
                        <td style="margin:0px;padding:0px;">
                            <select id="req_item" class="chosen-select" name="request_item">
                                <option value=""> -- </option>
                                <?php foreach ($items as $item) { ?>
                                    <option value="<?php echo $item->item_id; ?>"><?php echo $item->item_num.'  ('.$item->description.')'; ?></option>
                                <?php } ?>
                            </select>
                        </td>
                        <td style="margin:0px;padding:0px;">
                          <input style="width:100%;text-align: right;" type="number" id="req_qty" name="request_qty" class="form-control-custom">
                        </td>
                        <td style="margin:0px;padding:0px;">
                            <a style="width:100%;" class="btn btn-white" id="save_content"><i class="fa fa-plus success"></i></a>
                        </td>
                        
                      </tr> 
                    </thead>
                    </form>
                    <tbody id="tbodyadd_con" class="animate fadeIn">
                                                      
                    </tbody>
                  </table> 
          </div>
        </div> 

      </div>
    </div>
<script>
    $(document).ready(function(){
      var req_id;
      var greq_id = <?php echo json_encode($g_req_id); ?>;
      var markers=[];
        $(".chosen-select").chosen({width:"100%;"});
        $('#req_stat option:not(:selected)').attr('disabled', true).trigger('chosen:updated');
        $('#edit_wo_form').data('serialize',$('#edit_wo_form').serialize());
        $('#complete_wo_form').data('serialize',$('#complete_wo_form').serialize());
        if($('#cwo').val() == 'NEW'){
          $('#last_r').prop('readonly',true);
        }else if($('#cwo').val() == 'DIS'){
          $('#new_r').prop('readonly',true);
        }else if($('#cwo').val() == 'REC'){
          $('#last_r').prop('readonly',true);
        }else if($('#cwo').val() == 'REP'){
          $('#last_r').val('');$('#new_r').val('');
        }


        $('#req_add').click(function(){
          $('#wo_window').slideUp();
          $('#request_window').slideDown();
          $('#ins_req').show();$('#upd_req').hide();
          $('#req_add_content').hide();
        });

        $('#back_wo').click(function(){
          notifymsg('hide','hide');
          $('#request_window').slideUp();
          $('#wo_window').slideDown();
        });

        $('#back_woa').click(function(){
          notifymsg('hide','hide');
          $('#request_window').slideUp();
          $('#wo_window').slideDown();
        });

        $('#req_upd').click(function(){
          $('#wo_window').slideUp();
          $('#request_window').slideDown();
          $('#ins_req').hide();$('#upd_req').show();
          if($('#req_id').val() == ''){
            $('#req_id').val(greq_id);
          }
          
          get_req_data($('#req_id').val());
        })

        function get_req_data(id){
          $.ajax({
            type: "POST",
            url: "<?php echo base_url($this->session->userdata('forajax').'/get_req_data'); ?>",
            data: { "req_id" : id },
            dataType: "json",
            success: function(data){
              $.each(data,function(i,items){
                $('#wo_add_req input[name=request_num]').val(data[i].inv_request_num);
                $('#wo_add_req input[name=request_date').val(data[i].inv_request_date);
                $('#wo_add_req select[name=request_by]').val(data[i].inv_requested_by);
                $('#wo_add_req select[name=request_stat]').val(data[i].inv_request_status);
                $(".chosen-select").trigger("chosen:updated");

                generate_reqContents(id);
              });
            }
          });
        }

        $.validator.setDefaults({ ignore: ":hidden:not(select)" });
    $("#req_add_content").validate({
        rules: {
                req_sequence: {
                  required: true
                },
                request_item: {
                  required: true
                },
                request_qty: {
                  required: true,
                  number:true
                }
              }
            });

      function generate_reqContents(id){
        req_id = $('#req_id').val();
        console.log('samok - '+ id);
      $.ajax({
            type: "POST",
            url: "<?php echo base_url($this->session->userdata('forajax').'/view_req_contents'); ?>"+"/"+id,
            dataType: 'json',
        success: function(data){
              $('#tbodyadd_con').empty();
                      var trHTML = '';
                      $.each(data, function(i, item) {
                          trHTML += '<tr><input id="reqcon_id" type="hidden" value="'+ data[i].req_content_id +'"><td>' + data[i].sequence_num + '</td><td text-align:right;>' + data[i].item_num + ' ('+data[i].description+')' + '</td><td text-align:right;>' + data[i].inv_item_qty + '</td><td style="margin:0px;padding:0px;"><a style="width:100%;" class="btn btn-outline btn-danger del" id="ok_x"><i id="del_icon" class="fa fa-times success"></i></a></td></tr>';  
                      });
              $('#tbodyadd_con').append(trHTML);  
                },
                        complete: function() {
                           console.log('samok c - '+ id);
                        },
                        beforeSend: function(){
                          console.log('samok b - '+ id);
                        }      
            });
    }
    


    $('#save_content').click(function(){
      if($("#req_add_content").valid() == true){
         $.ajax({
              url: "<?php echo base_url($this->session->userdata('forajax') . '/insert_req_content'); ?>",
              method:'post',
              data: $('#req_add_content').serialize(),
              dataType:'json',
              success: function (data) {
                  if(data[0].error == 1){
                      notifymsg("danger",data[0].msg);
                  }else{
                      notifymsg("success",". . .Request Contents Added Successfully");
                      generate_reqContents($('#req_id').val());
                      // $('#tbodyadd_con').empty();
                      // var trHTML = '';
                      // $.each(data, function(i, item) {
                      //     trHTML += '<tr><td>' + data[i].sequence_num + '</td><td text-align:right;>' + data[i].item_num + ' ('+data[i].description+')' + '</td><td text-align:right;>' + data[i].inv_item_qty + '</td><td style="margin:0px;padding:0px;"><a style="width:100%;" class="btn btn-outline btn-danger del" id="ok_x"><i id="del_icon" class="fa fa-times success"></i></a></td></tr>';
                      // });
                      // $('#tbodyadd_con').append(trHTML);
                      $("#req_item option:first").attr('selected','selected').trigger('chosen:updated');
                      $('#req_add_content')[0].reset();
                  }  
              }
           });
        }

        // $('#tbodyadd_con').append("<tr><td>"+$('#sample_seq').val()+"</td><td>"+$('#sample_item').val()+"</td><td>"+$('#sample_qty').val()+"</td><td></td></tr>");
        // $('#sample_seq').val(''); $('#sample_item').val('1').change();  $('#sample_qty').val('');
    });  


        $("#wo_add_req").validate({
             rules :{
                  request_num:{
                      required: true
                  },
                  request_date:{
                      required: true
                  },
                  request_by:{
                      required: true
                  },
                  request_stat:{
                      required: true
                  }
            }
        });

        $('#submit_req_add').click(function(){
          if($('#wo_add_req').valid() == true){
            dataString = $("#wo_add_req").serialize();
            $.ajax({
              type: "POST",
              url: "<?php echo base_url($this->session->userdata('forajax').'/insert_request'); ?>",
              data: dataString+'&'+$.param({'maintain_id' : $('#maintain_id_2').val()}),
              dataType: 'json',
            success: function(data){
              if(data[0].error == 1){
                  notifymsg("danger",data[0].msg);
              }else{
                  notifymsg("success",". . .New Request Added Successfully");
                  mID = data[0].id; console.log(mID);
                  $('#req_add_content').show();
                  $('#req_id').val(mID);
                  $('#req_add').hide();
                  $('#req_upd').show();
                  $('#req_content').show();
                  $('#submit_req_add').attr('disabled','disabled');
                  $('#wo_add_req').find('input, button').attr('disabled','disabled');
                  // $('#rate_ena').attr('disabled','disabled');$('input').iCheck('update');
                 // $('#back_wo').html('Complete');
              }
            }      
           }); 
          }
        });

        $('#submit_req_upd').click(function(){
          if($('#wo_add_req').valid() == true){
            dataString = $("#wo_add_req").serialize();
            $.ajax({
              type: "POST",
              url: "<?php echo base_url($this->session->userdata('forajax').'/update_request'); ?>",
              data: dataString+'&'+$.param({'req_id' : $('#req_id').val()}),
              dataType: 'json',
            success: function(data){
              if(data[0].error == 1){
                  notifymsg("danger",data[0].msg);
              }else{
                   notifymsg("success",". . .Request Updated Successfully");
                  // mID = data[0].id; console.log(mID);

                  // $('#req_id').val(mID);
                  // $('#req_content').show();
                  // $('#submit_req_add').attr('disabled','disabled');
                  // $('#wo_add_req').find('input, button').attr('disabled','disabled');
                  // // $('#rate_ena').attr('disabled','disabled');$('input').iCheck('update');
                  // $('#back_wo').html('Complete');
              }
            }      
           }); 
          }
        });


      $(document).on('click','.btn.btn-outline.btn-danger.del',function(){
              var sad = $(this);
              var line_id    = $(this).closest('tr').children('#reqcon_id').val();
              swal({
                title: "Are you sure?",
                text: "This line in sequence will be deleted !",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Yes, delete it!",
                closeOnConfirm: false
            }, function (isConfirm) {
              if (isConfirm) {
                $.ajax({
                        type: "POST",
                        url: "<?php echo base_url($this->session->userdata('forajax') . '/delete_req_contents'); ?>",
                        data: {"line_id": line_id , "request_id" : req_id},
                        dataType: 'json',
                    success: function(data){
                        console.log(data);
                        if(data.length != 0){
                          if(data[0].error == 1){
                              notifymsg("danger",data[0].msg);
                          }else{
                          notifymsg("success",". . .Request Content Deleted Successfully");
                          generate_reqContents(req_id);
                          }
                         }else{
                           $('#tbodyadd_con').empty();
                         } 
                      }
                    });
                swal("Deleted!", "Request content has been deleted.", "success");
              }
            });
          });




// -----------------    END OF REQUEST


        $('#e_t_date').datepicker({
                keyboardNavigation: false,
                forceParse: false,
                autoclose: true,
                format: "yyyy-mm-dd"
        });
        $.validator.setDefaults({ ignore: ":hidden:not(select)" });

        $('#add_dev_btn_2').click(function(){
            $("#device_form_e").find(':input(:disabled)').prop('disabled',false);
            $("#device_form_e").find('select').prop('disabled',false);
            $('.chosen-select').trigger('chosen:updated');
            $('#device_window_e').slideToggle();
            if($(this).hasClass('active')){
                $('#add_dev_click').val('1');
            }else{$('#add_dev_click').val('0');}
            if($('#tits').html() == "Add Device"){
              initialize();
            }
         //console.log( $('#add_dev_click').val());
        });


        function initialize() {
           var mapProp = {
            center:new google.maps.LatLng(8.347557925845486,124.27363961935043),
            zoom:17,
            mapTypeId:google.maps.MapTypeId.SATELITE
          };
          var map=new google.maps.Map(document.getElementById("map_canvas"),mapProp);
            google.maps.event.addDomListener(window, 'load', initialize);

          map.addListener('click', function(e) {
            placeMarkerAndPanTo(e.latLng, map);
          });  
        // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
        }


        function placeMarkerAndPanTo(latLng, map) {
          DeleteMarkers();
          var marker = new google.maps.Marker({
            position: latLng,
            map: map
          });
          map.panTo(latLng);

          markers.push(marker);
          $('#e_dlat').val(latLng.lat());
          $('#e_dlng').val(latLng.lng());

        }


        function DeleteMarkers() {
        //Loop through all the markers and remove
            for (var i = 0; i < markers.length; i++) {
                markers[i].setMap(null);
            }
            markers = [];
        }
        $('#dev_info').click(function(){
            $('#device_window_e').slideToggle();
            $("#device_form_e").find(':input:not(:disabled)').prop('disabled',true);
            $("#device_form_e").find('select').prop('disabled',true);
            $('.chosen-select').trigger('chosen:updated');
        });

        $('#edit_wo_form').validate({
        rules :{
            edit_wo_assign:{
                required: true
            },
            edit_target_date:{
                required: true
            }
        },submitHandler: function(form){
           dataString = $("#edit_wo_form").serialize();
           if($('#hasDevice').val() == 'true'){
                  $.ajax({
                    type: "POST",
                    url: "<?php echo base_url($this->session->userdata('forajax') . '/update_work_order'); ?>",
                    data: dataString,
                    dataType: 'json',
                  success: function(data){
                    if(data[0].error == 1){
                        notifymsg("danger",data[0].msg);
                    }else{
                        notifymsg("success",". . .Rate Updated Successfully");
                        //close_edit(); active_search();
                        //$('#edits').attr('disabled', true);
                        $('#cancel_edit').hide();
                        $('#complete_btn_edit').show();
                    }
                  }
                 });
            }else{notifymsg('danger',"Please ADD a <b>Device</b>");}
        }
        });

        $('#complete_btn_edit').click(function(){
            close_edit(); active_search();
        });

        $('#complete_wo_form').validate({
        rules :{
            wo_new_reading:{
                required:true,
                number: true
            },
            wo_last_reading:{
              required:true,
              number: true
            }
        },submitHandler: function(form){
          dataString = $("#complete_wo_form").serialize();
          if($('#hasDevice').val() == 'true'){
            $.ajax({
                type: "POST",
                url: "<?php echo base_url($this->session->userdata('forajax') . '/update_work_order_comp'); ?>",
                data: dataString,
                dataType: 'json',
              success: function(data){
                if(data[0].error == 1){
                    notifymsg("danger",data[0].msg);
                }else{
                    notifymsg("success",". . .Work Order Completed Successfully");
                    //$('#edits').attr('disabled', true);
                    $('#cancel_edit').hide();
                    $('#complete_btn_edit').show();
                    //close_edit(); active_search();
                }
              }
         });
          }else{ notifymsg('danger',"Please ADD a <b>Device</b>");}
        }
        });

        function get_device_dtl(){
            $.ajax({
                type: "POST",
                url: "<?php echo base_url($this->session->userdata('forajax') . '/get_dev2'); ?>",
                data: {'account_id' : $('#acct').val(),'work_type' : $('#work_type').val() },
                dataType: 'json',
                success: function(data){
                    $('#device_form_e input[name=device_ass_id]').val(data[0].device_assignment_id);
                    $('#device_form_e input[name=account_id]').val(data[0].account_id);
                    $('#device_form_e input[name=dev_id]').val(data[0].device_id);
                    $('#device_form_e select[name=mom_meter]').val(data[0].mmeter_id);
                    $('#device_form_e input[name=e_devLat]').val(data[0].loc_latitude);
                    $('#device_form_e input[name=e_devLng]').val(data[0].loc_longitude);
                    $('#device_form_e select[name=item_num]').val(data[0].item_id);
                    $('#device_form_e select[name=dev_type]').val(data[0].device_type);
                    $('#device_form_e input[name=model_number]').val(data[0].model_number);
                    $('#device_form_e input[name=serial_number]').val(data[0].serial_number);
                    $('#device_form_e input[name=install_date]').val(data[0].install_date);
                    $('#device_form_e input[name=warranty_per]').val(data[0].warranty_period);
                    $('#device_form_e input[name=initial_read]').val(data[0].initial_reading);
                    $('#device_form_e input[name=last_read]').val(data[0].last_reading);
                    $('#device_form_e input[name=status]').val(data[0].status);
                    $('#device_form_e input[name=dev_remarks]').val(data[0].device_remarks);
                    $('.chosen-select').trigger('chosen:updated');
                    initialize_edit();
                }
            });
        }
        get_dev(1);
        function get_dev(num){
            console.log('maintain id is ' +$('#maintain_id_2').val());
            $.ajax({
                type: "POST",
                url: "<?php echo base_url($this->session->userdata('forajax') . '/get_dev'); ?>",
                data: {'maintain_id' : $('#acct').val(),'work_type' : $('#work_type').val() },
                dataType: 'json',
              success: function(data){
                console.log(data.length);
               //$('#hasDevice').val('true');
                if(data.length <= 0){
                    $('#hasDevice').val('false');
                    if($('#maintain_code_2').val() == 'DIS' || $('#maintain_code_2').val() == 'REC'){
                      $('#hasDevice').val('true');
                    }
                    console.log('empty');
                    if($('#maintain_code_2').val() == 'NEW' || $('#maintain_code_2').val() == 'REP'){
                        //$('#add_dev_btn_2').trigger('click');
                        //$('#add_dev_btn_2').hide();
                        $('#tits').html('Add Device');
                    }
                }else{
                    $('#hasDevice').val('true');
                    console.log('not empty');
                    if($('#maintain_code_2').val() == 'NEW' || $('#maintain_code_2').val() == 'REP'){
                        console.log('nots empty');
                    if(num == 1){
                        $('#add_dev_btn_2').trigger('click');
                    }
                        $('#add_dev_btn_2').hide();
                        $('#tits').html('Edit Device');
                        $('#save_device_2').hide();
                        $('#save_edit_device_2').show();
                        get_device_dtl();
                    }else{
                        //$('#add_dev_btn_2').show();
                        console.log('nota empty');
                        $('#save_device_2').hide();
                        $('#cancel_add_device_2').hide();
                        $('#dev_info').show();
                        get_device_dtl();
                    }
                }
              }
            });
        }

         function initialize_edit() {
                   var current=new google.maps.LatLng($('#e_dlat').val(),$('#e_dlng').val());
                   var sample = new google.maps.LatLng(8.397440728062685,124.59655725862831);
                   var mapProp = {
                    center:new google.maps.LatLng(8.397440728062685,124.59655725862831),
                    zoom:17,
                    mapTypeId:google.maps.MapTypeId.SATELITE
                  };

                 
                  var map=new google.maps.Map(document.getElementById("map_canvas"),mapProp);
                    google.maps.event.addDomListener(window, 'load', initialize_edit);


                   var marker=new google.maps.Marker({
                      position:current,
                      });
                    markers.push(marker);
                    marker.setMap(map);
                    map.panTo(current);

                  map.addListener('click', function(e) {
                    placeMarkerAndPanTo_edit(e.latLng, map);
                  });  
                // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
                }

                function placeMarkerAndPanTo_edit(latLng, map) {
                  DeleteMarkers();
                  var marker = new google.maps.Marker({
                    position: latLng,
                    map: map
                  });
                  map.panTo(latLng);

                  markers.push(marker);
                  $('#e_dlat').val(latLng.lat());
                  $('#e_dlng').val(latLng.lng());

                }
                function DeleteMarkers() {
                //Loop through all the markers and remove
                    for (var i = 0; i < markers.length; i++) {
                        markers[i].setMap(null);
                    }
                    markers = [];
                }

        $('#save_edit_device_2').click(function() {
            if($("#device_form_e").valid() == true){
                 $.ajax({
                        url: "<?php echo base_url($this->session->userdata('forajax') . '/update_dev'); ?>",
                        method:'post',
                        data: $('#device_form_e').serialize(),
                        dataType:'json',
                        success: function (data) {
                            if(data.err == 1){
                                notifymsg('danger','<b>Error</b>: '+data.msg);
                            }else{
                                notifymsg('success','<b>Success</b>: Data saved.');
                                $('#hasDevice').val('true');
                               // getDeviceEdit();
                                //$("#edit_data").load("<?php echo $this->session->userdata('forload') . '/edit_form/'; ?>" + sessionStorage.acct_entity_id_e);
                            }
                        },
                        complete: function() {
                            $("#save_edit_device_2").removeAttr("disabled");
                        },
                        beforeSend: function(){
                            $("#save_edit_device_2").attr("disabled", true);
                        }
                    });
                }
        });

        $('#save_device_2').click(function(){
            if($("#device_form_e").valid() == true){
                 $.ajax({
                      url: "<?php echo base_url($this->session->userdata('forajax') . '/insert_dev_edit'); ?>",
                      method:'post',
                      data: $('#device_form_e').serialize()+'&'+$.param({ 'account_id': $('#acct').val(), 'maintain_id' : $('#maintain_id_2').val() }),
                      dataType:'json',
                      success: function (data) {
                          $('#save_device_2').removeAttr('disabled');
                          if(data.err == 1){
                             notifymsg('danger','<b>Error</b>: '+data.msg);
                          }else{
                              get_dev(2);
                              // $('#tits').html('Edit Device');
                              // $('#hasDevice').val('true');
                              //$('#save_device_2').attr('disabled',true);
                              //$('#cancel_add_device').attr('disabled',true);
                              // $("#device_form_e").find(':input:not(:disabled)').prop('disabled',true);
                              // $("#device_form_e").find('select').prop('disabled',true);
                              $('.chosen-select').trigger('chosen:updated');
                              notifymsg('success','<b>Success</b>: Device saved.');
                          }
                      },beforeSend: function(){
                            $('#save_device_2').attr('disabled',true);
                      }
                   });
                }
        });

        function alert_cancel(){
            if($('#complete_wo_form').serialize()!=$('#complete_wo_form').data('serialize') || $('#edit_wo_form').serialize()!=$('#edit_wo_form').data('serialize') ){
                swal({
                    title: "Are you sure?",
                    text: "Your work will not be save",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "Leave",
                    cancelButtonText: "Stay",
                    closeOnConfirm: true,
                    closeOnCancel: true },
                function (isConfirm) {
                    if (isConfirm) {
                        close_edit(); active_search();
                        notifymsg("hide","hide");setter = 0;
                    } else {
                        swal("Cancelled");
                    }
                });
                }else{
                close_edit(); active_search();
                notifymsg("hide","hide");setter = 0;
            }
        }
        $('#cancel_edit').click(function () {
            alert_cancel();
         });
        $('#editX').click(function(){
            alert_cancel();
       });

         $("#device_form_e").validate({
             rules: {
                 item_num: {
                    required: true
                 },
                 dev_type: {
                    required: true
                 },
                 model_number: {
                    required: true
                 },
                 serial_number: {
                    required: true
                 }
             }
        });

    });
</script>